#include "stdio.h"
#include "pthread.h"
#include "stdlib.h"
#include "unistd.h"

#define THREAD_COUNT 20000

// 初始化互斥锁
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

// 线程函数
void *thread_fun(void *arg)
{
    // 加锁
    pthread_mutex_lock(&mutex);
    // 临界区代码
    int *sum = (int *)arg;
    (*sum)++;
    // 解锁
    pthread_mutex_unlock(&mutex);
    return NULL;
}

int main(int argc, char const *argv[])
{
    int sum = 0;
    // 创建线程
    pthread_t threads[THREAD_COUNT];
    for (int i = 0; i < THREAD_COUNT; i++)
    {
        pthread_create(&threads[i], NULL, thread_fun, &sum);
    }

    // 等待线程结束
    for (int i = 0; i < THREAD_COUNT; i++)
    {
        pthread_join(threads[i], NULL);
    }

    // 打印结果
    printf("sum = %d\n", sum);

    // 销毁互斥锁
    pthread_mutex_destroy(&mutex);

    

    return 0;
}
